package middleware

import (
	"ginstart/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

type JsonRes struct {
	Code    int
	Message string
	Data    interface{}
}

func AutoMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		get := c.GetHeader("token")
		if get == "" {
			c.JSON(http.StatusOK, gin.H{
				"response": JsonRes{
					Code:    500,
					Message: "没登录",
					Data:    nil,
				},
			})
			return
		}
		token, s2 := pkg.GetToken(get)
		if s2 != "" {
			c.JSON(http.StatusOK, gin.H{
				"response": JsonRes{
					Code:    500,
					Message: s2,
					Data:    nil,
				},
			})
			return
		}
		s3 := token["user"].(string)
		c.Set("userId", s3)
		c.Next()
	}
}
